package com.ysd.twocrm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ysd.twocrm.entity.RoleModules;
import com.ysd.twocrm.entity.Roles;
import com.ysd.twocrm.entity.RolesPermission;
import com.ysd.twocrm.entity.UserRoles;
import com.ysd.twocrm.mapper.*;
import com.ysd.twocrm.service.RolesService;
import com.ysd.twocrm.utils.UUID;
import org.apache.ibatis.annotations.Delete;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/roles")
//@RequiresRoles(value = "管理员")
public class RolesController {
    @Autowired
    private RolesMapper rolesMapper;
    @Autowired
    private UserRolesMapper userRolesMapper;
    @Autowired
    private StudentClassMapper studentClassMapper;
    @Autowired
    private RolesService rolesService;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private RoleModulesMapper roleModulesMapper;

    /*
     * @Description  查询全部角色
     * @param
     * @return java.lang.Object
     * @author liusupeng
     * @date 2020/4/11 18:13
     */
    @GetMapping
    public Object getAllRoles(){
        return rolesMapper.selectList(null);
    }
    /*
     * @Description 根据用户来查询当前用户所拥有的角色
     * @param userid
     * @return java.lang.Object
     * @author liusupeng
     * @date 2020/4/11 22:36
     */
@GetMapping("/1")
    public Object getAllRolesByUserId(Integer userid){


        return rolesMapper.getAllRolesNameById(userid);
    }
    /*
     * @Description  多条件查询角色，根据角色名称模糊查询
     * @param page
     * @param r
     * @return java.lang.Object
     * @author liusupeng
     *
     */
    @GetMapping("/2")
    @RequiresPermissions(logical = Logical.AND,value = {"roles:select"})
    public Object getAllRolesByName(Integer page, Roles r){

    return rolesService.LAYUI_ROLES(page,r);
    }
    /*
     * @Description 传入角色id用来判断是否在用户角色的中间表里存在 success:为空 false：有值
     * @param roleId
     * @return java.lang.Object
     * @author liusupeng
     *
     */
    @GetMapping("/3")
    public Object getAllIfUserRolesById(Integer roleId){

        List<UserRoles> userroleiflist = userRolesMapper.userroleiflist(roleId);
        if(userroleiflist.isEmpty()){
            return "success";
        }else{
            return "false";
        }
    }



    /*
     * @Description 根据用户id和角色id来为当前用户添加角色,
     * 判断当前设置的角色是管理员呢还是学生还是游客，其他都是员工，则修改当前用户在前台显示的
     * @param userRoles  用户id  角色id
     * @return java.lang.String
     * @author liusupeng
     * @date 2020/4/11 23:45
     */
    @PostMapping
    public String addUsersRolesById(UserRoles userRoles){
        int insert = userRolesMapper.insert(userRoles);//添加
        Integer admin = userRolesMapper.getAllRoleNameById("管理员");
        Integer youke = userRolesMapper.getAllRoleNameById("游客");
        Integer student=userRolesMapper.getAllRoleNameById("学生");
        if(userRoles.getRoleId()==admin){
            usersMapper.exitUsersRolesId(userRoles.getUserId(),0);
         }else if(userRoles.getRoleId()==youke){
            usersMapper.exitUsersRolesId(userRoles.getUserId(),3);
        }else if(userRoles.getRoleId()==student){
            usersMapper.exitUsersRolesId(userRoles.getUserId(),1);
        }else{
            usersMapper.exitUsersRolesId(userRoles.getUserId(),2);
        }

        if(insert>0){
            return "success";
        }
        return "false";
    }
    /*
     * @Description 添加角色信息
     * @param r
     * @return java.lang.String
     * @author liusupeng
     * @date 2020/4/15 11:11
     */
    @PostMapping("/1")
    @RequiresPermissions(value = "roles:add")
    public String addRoles(Roles r){
   try {
       int insert = rolesMapper.insert(r);
       if(insert>0){
           return "success";
       }

   }catch (Exception e){
       return "sqlfalse";
   }
        return "false";
    }
    /*
     * @Description 设置角色权限，根据用户id和传来的pid（权限id）来判断传来的是权限id还是什么，如果是权限id
     * 则对角色权限表进行操作，先根据角色id来删除，然后在添加
     * 还要先删除角色模块表和角色权限表然后在去判断是uid类型的？还是其他类型的 如果是uid类型的那就代表是权限表如果不是那就是角色模块表
     * 通过这个来控制就行
     * @param pid
     * @param roleId
     * @return java.lang.Object
     * @author liusupeng
     * @date 2020/4/19 15:17
     */
@PostMapping("/2")
    public Object getAllPermission(String pid,Integer roleId){
    roleModulesMapper.delModulesByRoleId(roleId);//删除模块角色表当前角色的模块
              permissionMapper.delPermissionRolesByRolesId(roleId);//删除角色权限表当前角色的权限
    String[] split = pid.split(",");
    for(int i=0;i<split.length;i++){
        if(UUID.checkIsUUid(split[i])==true){
            System.out.println(split[i]+"no异常");
               permissionMapper.insertPermissionRoles(roleId,split[i]);

        }else{
            roleModulesMapper.addModulesByRoleIdd(Integer.valueOf(split[i]),roleId);
            System.out.println(split[i]+">=异常");


        }
    }

    return "success";
    }


    /*
     * @Description 根据角色的主键id来修改角色名称
     * @param r
     * @return java.lang.String
     * @author liusupeng
     * @date 2020/4/15 18:32
     */
    @PutMapping
    @RequiresPermissions(value = "roles:update")
    public String exitRolesById(Roles r){

       try {
           int i = rolesMapper.updateById(r);
           if(i>0){
               return "success";
           }
           return "false";
       }catch (Exception e){
     return "sqlfalse";
       }
    }
    /*
     * @Description 根据用户id和角色id来为当前用户删除角色,并且首先要去除班级里和他有关联的角色
     * @param userRoles  用户id  角色id
     * @return java.lang.String
     * @author liusupeng
     * @date 2020/4/11 23:45
     */
    @DeleteMapping
    public String delUsersRolesById(UserRoles userRoles){

        //修改班级里和辅导员和教员有关联的人
        Integer fudaoyuan = userRolesMapper.getAllRoleNameById("辅导员");
        if(userRoles.getRoleId()==fudaoyuan){
            studentClassMapper.exitStudentClassByIstId(userRoles.getUserId());
        }
        Integer jiaoyuan = userRolesMapper.getAllRoleNameById("教员");
        if(userRoles.getRoleId()==jiaoyuan){
            studentClassMapper.exitStudentClassByTeaId(userRoles.getUserId());
        }
        //删除用户角色
        int delete = userRolesMapper.delUsersRolesById(userRoles.getUserId(),userRoles.getRoleId());
        if(delete>0){
            //删除完了开始判断当前用户角色还包含某个角色不，如果包含了修改当前用户表里的身份
            Integer admin = userRolesMapper.getAllRoleNameById("管理员");
            Integer youke = userRolesMapper.getAllRoleNameById("游客");
            Integer student=userRolesMapper.getAllRoleNameById("学生");
            QueryWrapper<UserRoles> queryWrapper=new QueryWrapper<UserRoles>();
            queryWrapper.eq("userId",userRoles.getUserId());
            List<UserRoles> userRoles1 = userRolesMapper.selectList(queryWrapper);//查询当前用户的全部用户角色

                for(UserRoles rs:userRoles1){
                if(rs.getRoleId()==admin){
                    System.out.println("移除管理员");
                    usersMapper.exitUsersRolesId(userRoles.getUserId(),0);
                    break;
                }else if(rs.getRoleId()==youke){
                    System.out.println("移除游客");
                    usersMapper.exitUsersRolesId(userRoles.getUserId(),3);
                    break;
                }else if(rs.getRoleId()==student){
                    System.out.println("移除学生");
                    usersMapper.exitUsersRolesId(userRoles.getUserId(),1);
                    break;
                }else{
                    System.out.println("移除员工");
                    usersMapper.exitUsersRolesId(userRoles.getUserId(),2);
                    break;
                }
            }
            return "success";
        }
        return "false";
    }

    /*
     * @Description 根据角色id来删除角色表以及用户角色表
     * @param roleId
     * @param pwd
     * @return java.lang.String
     * @author liusupeng
     * @date 2020/4/15 11:47
     */
    @DeleteMapping("/1")
    @RequiresPermissions(value = "roles:delete")
    public String deleteRoles(Integer roleId,String pwd){

           if(pwd.equals("admin")){
               int i = rolesMapper.deleteById(roleId);//删除角色表
               if(i>0){
                   userRolesMapper.delUserRolesByRoleId(roleId);//删除用户角色表
                   return "success";
               }

           }
        return "false";
    }


}
